﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;

namespace ReportGenerators.QuanLyKho
{
    public partial class FrmThongKeNhapXuatTonNhanh : BasicForms.FrmClose
    {
        public FrmThongKeNhapXuatTonNhanh()
        {
            InitializeComponent();
        }

        private void FrmThongKeNhapXuatTonNhanh_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                dtNgayKetThuc.DateTime = System.DateTime.Now;

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                if (GeneralLibs.LocalSettings.HeThong.KhoID is Guid)
                    cmbKho.EditValue = GeneralLibs.LocalSettings.HeThong.KhoID;
                else
                    cmbKho.EditValue = Guid.Empty;

                cmbNhomVatTuHangHoa.DataSource = DanhMucNhomVatTuHangHoa.Instance.DataView;
                cmbNhomVatTuHangHoa.DisplayColumn = "Ten";
                cmbNhomVatTuHangHoa.ValueColumn = "ID";
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ten", "Tên");

                dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
                gridControlDsVatTuHangHoa.DataSource = dsThongKeNhapXuatTonNhanh.VatTuHangHoa;
                gridControl.DataSource = dsThongKeNhapXuatTonNhanh.Detail;
            }
            catch (Exception ex)
            {
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }
            chkChooseAllVatTuHangHoa.Checked = false;
            FormatNumberInGridView(gridViewDsVatTuHangHoa);
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }

        private void cmbNhomVatTuHangHoa_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhomVatTuHangHoa.EditValue = Guid.Empty;
        }
        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbNhomVatTuHangHoa.EditValue is Guid && (Guid)cmbNhomVatTuHangHoa.EditValue != Guid.Empty)
            {
                //Dieu kien loc la ID = cmbNhomVatTuHangHoa.EditValue + ID cac nhom con.
                string filterNhomCon = "CONVERT('{" + cmbNhomVatTuHangHoa.EditValue.ToString() + "}','System.Guid'), ";
                DanhMucNhomVatTuHangHoa cacNhomCon = DanhMucNhomVatTuHangHoa.Instance.GetNhomVatTuHangHoaCon((Guid)cmbNhomVatTuHangHoa.EditValue);
                foreach (NhomVatTuHangHoa nhomCon in cacNhomCon)
                {
                    filterNhomCon += "CONVERT('{" + nhomCon.ID + "}','System.Guid'), ";
                    //filterNhomCon += string.Format(", '{0}'", nhomCon.ID);
                }
                if (filterNhomCon.EndsWith(", ")) filterNhomCon = filterNhomCon.Remove(filterNhomCon.Length - 2);

                dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Clear();
                string filter = string.Format("NhomVatTuHangHoaID IN ({0}) AND TrangThai = 1 ", filterNhomCon);
                dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Filter(filter).DataView.ToTable());
            }
            else
            {
                dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Clear();
                dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
            }
            chkChooseAllVatTuHangHoa.Checked = false;
            chkChooseAllVatTuHangHoa.Checked = true;
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            BasicForms.FrmProgressBar.StartShowProgress();
            try
            {
                SqlCommand cmd = con.CreateCommand();

                string vatTuHangHoaCondition = "1 = 1";
                if (!chkChooseAllVatTuHangHoa.Checked)
                {
                    vatTuHangHoaCondition = "A.VatTuHangHoaID IN  (";
                    foreach (DataRow row in dsThongKeNhapXuatTonNhanh.VatTuHangHoa.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }

                if (cmbKho.EditValue != null && (Guid)cmbKho.EditValue != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT B.Ma, B.Ten, B.GiaBia, A.TongNhap, A.TongXuat, A.Ton, A.DonGia, A.ThanhTien \n" +
                                                "FROM TheoDoiNhapXuatTon A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoaID = B.ID \n" +
                                                "WHERE A.ID = (SELECT Top 1 ID  \n" +
                                                "				FROM TheoDoiNhapXuatTon sub  \n" +
                                                "				WHERE sub.VatTuHangHoaID = A.VatTuHangHoaID AND sub.KhoID = A.KhoID AND sub.KhoID = '{0}'\n" +
                                                "				        AND sub.ThoiDiem <= @ThoiDiemBaoCao \n" +
                                                "				ORDER BY ThoiDiem DESC) \n" +
                                                "       AND ({1})",
                                                (Guid)cmbKho.EditValue, vatTuHangHoaCondition);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT B.Ma, B.Ten, B.GiaBia, SUM(A.TongNhap) TongNhap, SUM(A.TongXuat) TongXuat, SUM(A.Ton) Ton,  \n" +
                                 "CASE WHEN SUM(A.Ton) = 0 THEN 0 \n" +
                                 "ELSE SUM(A.ThanhTien) / SUM(A.Ton)  \n" +
                                 "END DonGia, SUM(A.ThanhTien) ThanhTien \n" +
                                 "FROM TheoDoiNhapXuatTon A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoaID = B.ID  \n" +
                                 "WHERE A.ID IN (SELECT ID   \n" +
                                 "               FROM TheoDoiNhapXuatTon sub   \n" +
                                 "               WHERE ThoiDiem >= (SELECT MAX(ThoiDiem) FROM TheoDoiNhapXuatTon sub2  \n" +
                                 "                                   WHERE sub2.KhoID = A.KhoID AND sub2.VatTuHangHoaID = A.VatTuHangHoaID \n" +
                                 "                                   ) \n" +
                                 "               AND sub.VatTuHangHoaID = A.VatTuHangHoaID AND sub.KhoID = A.KhoID \n" +
                                 "               )\n" +
                                 "       AND {0} \n" +
                                 "GROUP BY 	B.Ma, B.Ten, B.GiaBia	 \n" +
                                 "ORDER BY Ma	 \n",
                                 vatTuHangHoaCondition);
                }
                
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemBaoCao", dtNgayKetThuc.DateTime);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeNhapXuatTonNhanh.Detail.Clear();
                da.Fill(dsThongKeNhapXuatTonNhanh.Detail);
                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            gridControl.ShowPrintPreview();
        }
    }
}
